package com.sise.stuteaintersys.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sise.stuteaintersys.bean.base.ModifyResponse;
import com.sise.stuteaintersys.bean.entity.*;
import com.sise.stuteaintersys.bean.protocol.NetResult;
import com.sise.stuteaintersys.bean.vo.ExamResultVO;
import com.sise.stuteaintersys.bean.vo.HomeworkDateVO;
import com.sise.stuteaintersys.bean.vo.HomeworkResultVO;
import com.sise.stuteaintersys.locallibs.enums.ModifyEnum;
import com.sise.stuteaintersys.mapper.*;
import com.sise.stuteaintersys.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName TeacherServiceImpl
 * @Description
 * @Date 2019/1/3 16:32
 * @Version 1.0
 **/

@Service
@Slf4j
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    Mapper dozerMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    ProfessionTypeMapper professionTypeMapper;
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    ExamMapper examMapper;
    @Autowired
    ExamCourseMapper examCourseMapper;
    @Autowired
    DownloadInfoMapper downloadInfoMapper;
    @Autowired
    HomeworkMapper homeworkMapper;
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    ExamResultMapper examResultMapper;
    @Autowired
    HomeworkResultMapper homeworkResultMapper;


    @Override
    public Course getCourseById(Integer id) {
        return courseMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<Course> listCourse(Integer pageNum, Integer pageSize, Integer id) {
        PageHelper.startPage(pageNum,pageSize);
        List<Course> list = courseMapper.selectCourseByTeacherId(id);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Course> finishedCourse(Integer pageNum, Integer pageSize, Integer id) {
        PageHelper.startPage(pageNum, pageSize);
        List<Course> list = courseMapper.selectFinishedCourse(id);
        return new PageInfo<>(list);
    }

    @Override
    public ModifyResponse insertCourse(Course course) {
        ModifyResponse modifyResponse = new ModifyResponse();
        course.setGmtCreate(new Date());
        course.setGmtModified(new Date());
        try {
            int s = courseMapper.insert(course);
            modifyResponse.setNumber(s);
            if (s==0)
            {
                modifyResponse.setStatus(false);
                modifyResponse.setMsg("该课程名字已使用");
                return modifyResponse;
            }
            modifyResponse.setStatus(true);
            modifyResponse.setMsg(ModifyEnum.COURSEADDSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.COURSEADDERROR.getMsg());
            return modifyResponse;
        }

    }

    @Override
    public ModifyResponse updateCourse(Course course) {
        ModifyResponse modifyResponse = new ModifyResponse();
        try {
            course.setGmtModified(new Date());
            int number = courseMapper.updateByPrimaryKeySelective(course);
            modifyResponse.setStatus(true);
            modifyResponse.setNumber(number);
            modifyResponse.setMsg(ModifyEnum.COURSEUNDETSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.COURSEADDERROR.getMsg());
            return modifyResponse;
        }
    }


    @Override
    public ModifyResponse deleteCourse(Integer id) {
        ModifyResponse modifyResponse = new ModifyResponse();
        try {
            int number = courseMapper.deleteByPrimaryKey(id);
            modifyResponse.setStatus(true);
            modifyResponse.setNumber(number);
            modifyResponse.setMsg(ModifyEnum.COURSEDEFSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.COURSEDEFERRER.getMsg());
            return modifyResponse;
        }
    }

    //作业
    @Override
    public PageInfo<HomeworkDateVO> listHomework(Integer pageNum, Integer pageSize, Integer courseId) {
        PageHelper.startPage(pageNum, pageSize);
        List<String> list = homeworkMapper.listHomework(courseId);
        List<HomeworkDateVO> dateList = new ArrayList<>();
        for (String d : list) {
            HomeworkDateVO s = new HomeworkDateVO();
            s.setDate(d);
            dateList.add(s);
        }
        return new PageInfo<>(dateList);
    }

    @Override
    public List<Homework> getHomework(Date date,Integer courseId) {
        List<Homework> list = homeworkMapper.getHomework(date,courseId);
        return list;
    }

    @Override
    public ModifyResponse insertHomework(String list) {
        ModifyResponse modifyResponse = new ModifyResponse();
        List<Homework> homeworkList = JSONArray.parseArray(list, Homework.class);
        for (Homework homework : homeworkList) {
            homework.setGmtModified(new Date());
            homework.setGmtCreate(new Date());
        }
        try {
            int number = homeworkMapper.insertBatch(homeworkList);
            modifyResponse.setStatus(true);
            modifyResponse.setNumber(number);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKADDSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKADDERROR.getMsg());
            return modifyResponse;
        }
    }

    @Override
    public ModifyResponse updateHomework(Homework homework) {
        ModifyResponse modifyResponse = new ModifyResponse();
        try {
            int number = homeworkMapper.updateByPrimaryKeySelective(homework);
            modifyResponse.setStatus(true);
            modifyResponse.setNumber(number);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKUNDETSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKUNDETERRED.getMsg());
            return modifyResponse;
        }
    }

    @Override
    public ModifyResponse deleteHomework(Integer id) {
        ModifyResponse modifyResponse = new ModifyResponse();
        try {
            int number = homeworkMapper.deleteByPrimaryKey(id);
            modifyResponse.setStatus(true);
            modifyResponse.setNumber(number);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKDEFSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKDEFERRER.getMsg());
            return modifyResponse;
        }
    }

    @Override
    public ModifyResponse deleteListHomework(Date date) {
        ModifyResponse modifyResponse = new ModifyResponse();
        try {
            int number = homeworkMapper.deleteListByDate(date);
            modifyResponse.setStatus(true);
            modifyResponse.setNumber(number);
            modifyResponse.setNumber(number);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKDEFSUCCESS.getMsg());
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg(ModifyEnum.HOMEWORKDEFERRER.getMsg());
            return modifyResponse;
        }
    }

    @Override
    public List<HomeworkResult> listHomeworkResult(Integer courseId) {
        return homeworkResultMapper.selectHomework(courseId);
    }

    @Override
    public HomeworkResultVO findResultContent(Date date, Integer courseId, Integer studentId) {
        HomeworkResultVO homeworkResultVO = new HomeworkResultVO();
        HomeworkResult homeworkResult = homeworkResultMapper.select(courseId, studentId, date);
        List<Homework> list = homeworkMapper.getHomework(date, courseId);
        homeworkResultVO.setHomeworkResult(homeworkResult);
        homeworkResultVO.setHomeworkList(list);
        list = homeworkMapper.getHomework(date, courseId);
        return homeworkResultVO;
    }

    //留言板
    @Override
    public PageInfo<Message> listMessage(Integer pageNum, Integer pageSize, Integer id) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> list = messageMapper.selectAllMessage(id);
        return new PageInfo<>(list);

    }

    @Override
    public NetResult responseMessage(Message message) {
        message.setGmtModified(new Date());
        message.setAnswerTime(new Date());
        try {
            messageMapper.updateByPrimaryKeySelective(message);
            return NetResult.okadddata(ModifyEnum.MESSAGEUNDETSUCCESS.getCode(), ModifyEnum.MESSAGEUNDETSUCCESS.getMsg(), message);
        } catch (Exception e) {
            return NetResult.error(ModifyEnum.MESSAGEUNDETERRED.getCode(), ModifyEnum.MESSAGEUNDETERRED.getMsg());
        }
    }

//试卷

    @Override
    public PageInfo<ExamCourse> listExam(Integer pageNum, Integer pageSize, Integer courseId) {
        PageHelper.startPage(pageNum, pageSize);
        List<ExamCourse> list = examCourseMapper.selectExamByCourseId(courseId);
        return new PageInfo<>(list);
    }

    @Override
    public List<Question> listQuestion(String examType, String id) {
        List<Question> list = questionMapper.selectExam(id + examType);
        return list;
    }

    @Override
    @Transactional
    public ModifyResponse insertExam(ExamCourse examCourse) {
        ModifyResponse modifyResponse = new ModifyResponse();
        examCourse.setGmtCreate(new Date());
        examCourse.setGmtModified(new Date());
        examCourse.setExamType(examCourse.getExamType());
       try {
           List<Question> list = questionMapper.selectRandom(examCourse.getCourseId());
           //插入课程与试卷类型表中
            int check = examCourseMapper.insert(examCourse);
            if(check==0){
                modifyResponse.setNumber(check);
                modifyResponse.setStatus(false);
                modifyResponse.setMsg("已存在相同试卷名");
                return modifyResponse;
            }
            examCourse.setExamType(examCourse.getCourseId() + examCourse.getExamType());
            List<Exam> examList = new ArrayList<>();
            for (Question i : list) {
                Exam exam = dozerMapper.map(examCourse, Exam.class);
                exam.setQuestionId(i.getId());
                examList.add(exam);
            }
            //插入试卷与题号表中
            int number = examMapper.insertBatch(examList);
            modifyResponse.setNumber(number);
            modifyResponse.setStatus(true);
            modifyResponse.setMsg("增加试卷成功");
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setStatus(false);
            modifyResponse.setMsg("题库中并无课程试题");
            return modifyResponse;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModifyResponse deleteExam(ExamCourse course) {
        ModifyResponse modifyResponse = new ModifyResponse();
        try {
            examMapper.deleteByExamType(course.getCourseId() + course.getExamType());
            examCourseMapper.delete(course);
            modifyResponse.setMsg("删除成功");
            modifyResponse.setStatus(true);
            return modifyResponse;
        } catch (Exception e) {
            modifyResponse.setMsg("删除失败");
            modifyResponse.setStatus(false);
            return modifyResponse;

        }
    }
    @Override
    public List<ExamResult> listResult(Integer courseId) {
        return examResultMapper.selectExam(courseId);
    }

    @Override
    public ExamResultVO findExamResult(String examType, Integer courseId, Integer studentId) {
        ExamResultVO examResultVO = new ExamResultVO();
        ExamResult examResult = examResultMapper.select(courseId, studentId, examType);
        List<Question> list = questionMapper.selectExam(courseId + examType);
        examResultVO.setExamResult(examResult);
        examResultVO.setQuestionList(list);
        return examResultVO;
    }

    @Override
    public List<ProfessionType> listProfession() {
        return professionTypeMapper.select();
    }

    @Override
    public boolean saveExcelInfo(File file, Integer courseId) throws Exception {
        //获取数据流放到Excel中处理,加入判断是否为Excel文件
        boolean excel = !(file.isFile() && (file.getName().endsWith("xls") || file.getName().endsWith("xlsx")));
        if(excel){
            throw new Exception("文件不是Excel");
        }
        HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(file)));
        int numberOfSheets = workbook.getNumberOfSheets();
        //定义取Excel一行中的前6列
        int res = 0;
        for (int i = 0; i < numberOfSheets; i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);
            for(Row row:sheet){
//                试题实体
                Question question = new Question();
                question.setGmtCreate(new Date());
                question.setGmtModified(new Date());
                question.setTitle(row.getCell(0).toString());
                question.setOptionA(row.getCell(1).toString());
                question.setOptionB(row.getCell(2).toString());
                question.setOptionC(row.getCell(3).toString());
                question.setOptionD(row.getCell(4).toString());
                question.setAnswer(row.getCell(5).toString());
                question.setCourseId(courseId);
                res += questionMapper.insert(question);
            }
        }
        return res>0;
    }
}
